package com.doge.calcalbum.business.guide

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.setPadding
import com.doge.calcalbum.databinding.LayoutGuideNoteBinding
import com.doge.calcalbum.utils.lifecycleOwner
import com.doge.calcalbum.utils.spReadBoolean
import com.doge.calcalbum.utils.spWrite
import com.doge.calcalbum.utils.systemWindowInsetsTop

class GuideNoteLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs) {
    private val binding = LayoutGuideNoteBinding.inflate(LayoutInflater.from(context), this)

    init {
        lifecycleOwner?.let { systemWindowInsetsTop.observe(it) {
            binding.fitsSys.setPadding(it / 2)
        }}
    }

    fun display() {

        binding.root.setOnClickListener {
            completed()
            (parent as? ViewGroup?)?.removeView(this)
        }
    }

    companion object {
        fun completed() = spWrite("nt", false, "g")
        private var attached: Boolean? = null
        private val firstTime: Boolean get() = spReadBoolean("nt", true, "g")
        fun attach(view: ViewGroup): GuideNoteLayout? {
            if (attached == true) return null

            attached = true
            if (firstTime) {
                val viewGuide = GuideNoteLayout(view.context)
                view.addView(viewGuide)
                viewGuide.display()
                return viewGuide
            }

            return null
        }
    }


}